<?php

namespace App\Recharge\Logic;


use App\Recharge\Api\Fulu;
use App\Models\Mysql\XnSupplierGoods;
use App\Recharge\Bean\SupplierApiConfigBean;
use App\Models\Admin\InterfaceConfiguration;
use App\Recharge\Exceptions\SuspensionOfEnforcement;

class GoodLogic extends BaseLogic
{

    /**
     * 商品价格检测
     *
     * @param float|string|int $price
     * @param array $child
     * @param InterfaceConfiguration $api
     * @param SupplierApiConfigBean $config
     * @return void
     * @throws SuspensionOfEnforcement
     */
    function goodPriceToFilter(float|string|int $price, array $child, InterfaceConfiguration $api, SupplierApiConfigBean $config): void
    {
        // 判断销售价是否小于进价
        if ($price < $child['unit_price']) {
            $errorMessage = '子商品进价大于价格上限:[子商品 => '.$child['unit_price'].'] | [主商品 => '.$price.']';
            throw new SuspensionOfEnforcement($errorMessage);
        }
        // 检测第三方商品进价
        $this->thirdGoodUnitPriceCheck($api, $config, $child);
    }

    /**
     * @param InterfaceConfiguration $api
     * @param SupplierApiConfigBean $config
     * @param array|XnSupplierGoods $good
     * @return void
     * @throws SuspensionOfEnforcement
     */
    function thirdGoodUnitPriceCheck(InterfaceConfiguration $api, SupplierApiConfigBean $config, array|XnSupplierGoods $good): void
    {
        if (str_starts_with($api->en, 'fulu')) {
            $result = Fulu::new()->good($api, $config, $good['goods_code']);
            if (!$result->isResult()) {
                throw new SuspensionOfEnforcement($result->getErrMessage());
            }
            if ($result->getUnitPrice() > $good['unit_price']) {
                $errorMessage = '当前价格为['.$result->getUnitPrice().'[元，子商品实际价格['.$good['unit_price'].']低于进价';
                throw new SuspensionOfEnforcement($errorMessage);
            }
        }
    }
}
